package v1

import (
	"ginblog/middeware"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

// 登录页面 后台登录
func Login(ctx *gin.Context) {
	var user model.User
	var token string

	// 绑定数据并进行验证
	_ = ctx.ShouldBindJSON(&user)
	user, code = model.CheckLogin(user.Username, user.Password)

	if code == errmsg.SUCCESS {
		setToken(ctx, user)

	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"status":  code,
			"data":    user.Username,
			"id":      user.ID,
			"message": errmsg.GetErrMsg(code),
			"token":   token,
		})
	}

}

// 前台登录
func Login1(ctx *gin.Context) {
	var user model.User
	_ = ctx.ShouldBindJSON(&user)
	var code int
	user, code = model.CheckLoginFront(user.Username, user.Password)
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    user.Username,
		"message": errmsg.GetErrMsg(code),
	})

}

func Home(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "user/home.html", gin.H{
		"title":   "Home",
		"message": "success",
	})
}

// 生成token 1.0 前后端不分离的
func CreateToken(ctx *gin.Context, user model.User) (token string, err error) {
	j := middeware.NewJWT()
	claims := middeware.MyClaims{
		Username: user.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
			Issuer:    "ginBlog",
		},
	}
	token, err = j.CreateToken(claims)
	if err != nil {
		return "", err
	}
	return token, nil
}

// token生成函数
func setToken(ctx *gin.Context, user model.User) {
	j := middeware.NewJWT()
	claims := middeware.MyClaims{
		Username: user.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
			Issuer:    "ginBlog",
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"status":  errmsg.ERROR,
			"message": errmsg.GetErrMsg(errmsg.ERROR),
			"token":   token,
		})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status":  errmsg.SUCCESS,
		"message": errmsg.GetErrMsg(errmsg.SUCCESS),
		"data":    user.Username,
		"id":      user.ID,
		"token":   token,
	})
	return
}
